import re
import os
import sys
from xlchk import chk_call
from chardet import detect

TEMPALTE_FILE_CONT = '''
### VER.MD
---
$cont
'''

TEMPALTE_TAGCHG_CONT = '''
**$tag**
```
$chg
```
'''


class VerChg(object):
    @staticmethod
    def comp_tagchg(tag1, tag2):
        strf = ""
        cmd_str = "git log --pretty='%s' ^{tag1} {tag2}".format(
            tag1=tag1, tag2=tag2)
        list_chg = os.popen(cmd_str).readlines()
        for line in list_chg:
            codesc = detect(line)
            if codesc.has_key("encoding") and codesc.get("encoding") != None:
                if line.upper().find("DEV") == -1 and \
                        line.upper().find("MERGE") == -1:
                    if codesc["encoding"].find("ISO-") != -1:
                        strf += line.decode("gbk").encode("utf8")
                    else:
                        try:
                            strf += line.decode(codesc["encoding"]
                                                ).encode("utf8")
                        except:
                            print ("[ERROR]:unknow encoding of msg in tag<%s>, codesc is %s \n%s" % (
                                tag2, codesc, line))
            else:
                strf += line
        return strf

    @staticmethod
    def chk_taglist(starv):
        tags = []

        list_tags = os.popen("git tag --list").readlines()
        idx_s = len(list_tags) - list_tags.index(starv + "\n")
        for tag in list_tags[-idx_s::]:
            tags.append(re.sub("[\r\n]", "", tag))
        return tags

    @classmethod
    def execute(cls, tfile, starv="v2.5.0"):
        ret = ""

        tags = VerChg.chk_taglist(starv)
        print(tags, '-->>tags')
        for i in range(len(tags)):
            if i < len(tags) - 1:
                ret += TEMPALTE_TAGCHG_CONT.replace("$chg", VerChg.comp_tagchg(tags[i], tags[i + 1])) \
                    .replace("$tag", tags[i + 1])
        with open(tfile, "w") as vf:
            vf.write(TEMPALTE_FILE_CONT.replace("$cont", ret))
            vf.close()


if __name__ == "__main__":
    print("======================================")
    print("===========GIT_TAGLOG v0.1============")
    print("======================================")

    def bin_call():
        if len(sys.argv) < 2:
            print("Input the file to stdout!!")
        else:
            VerChg.execute(sys.argv[1])
    chk_call(bin_call)
